<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 9/19/14
 * Time: 9:28 PM
 */

namespace Backend\Modules\Video\Controllers;

use Common\library\Common;
use Library\Constant\Constant;
use \Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\VideoDescription;
use Backend\Modules\Video\Models\VideoCategoryLink;
use Backend\Modules\Video\Models\Artist ;
use Backend\Modules\Video\Models\VideoArtistLink;
use Backend\Modules\Video\Models\VideoFile;
use Backend\Modules\Video\Models\VideoFileLink;
use Backend\Modules\Video\Models\VideoGroup;
use Backend\Modules\Video\Models\VideoGroupLink;
use Backend\Modules\Video\Forms\FormCreateVideo;

use Library\Upload\UploadFile as UploadFile;
use Phalcon\Mvc\View;
use Phalcon\Http\Response;

class VideoController extends \BackendController
{
    public $urlVideo = 'video';
    public static $ITEM_PER_PAGE = 20;
    public function indexAction()
    {
        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $video = Video::find();


        /*$videoBuilder = $this->modelsManager->createBuilder()
                                        ->from(array('video' => '\Backend\Modules\Video\Models\Video'))
                                        ->groupBy("video.id")
                                        ->join('\Backend\Modules\Video\Models\VideoDescription' , 'video.id = video_description.video_id' , 'video_description')
                                        //->join('\Backend\Modules\Video\Models\VideoDescription' , 'video.id = video_description.video_id' , 'video_description')
                                        //->join('\Backend\Modules\Video\Models\VideoDescription' , 'video.id = video_description.video_id' , 'video_description')
                                        ->limit(20)
                                        ->orderBy('video.id')
                                        ->getQuery()
                                        ->execute();

        foreach($videoBuilder as $item)
        {
            die(print_r($videoBuilder->toArray()));
        }*/

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $video,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                // We will use Bootstrap framework styles
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                // Range window will be 5 pages
                'rangeLength' => 5,
                // Just a string with URL mask
                'urlMask'     => '?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
    }

    public function createAction()
    {
        $uploadFile = new UploadFile();
        $uploadFile->loadLibraryScript();
        $this->assets
            ->addJs('vendor/backend/js/video/controller/video.js');

        $form = new FormCreateVideo();

        if($this->request->isPost())
        {
            if($form->isValid($this->request->getPost()) != false)
            {
                $video = new Video();
                //$form->bind($this->request->getPost() , $video);
                $video->assign(array(
                    'imdb' => 0 ,
                    'national_id' => $this->request->getPost('duration'),
                    'duration' => $this->request->getPost('duration'),
                    'year_product' => $this->request->getPost('year_product'),
                    'year_publish' => $this->request->getPost('year_publish'),
                    'is_vip' => 'N',//$this->request->getPost('is_vip'),
                    'hot_month' => $this->request->getPost('hot_month') ? $this->request->getPost('hot_month') : 'N',
                    'total_view' => 0,
                    'created_user'          => 1,//$this->request->getPost('status', 'int'),
                    'published_user'        => 1,//$this->request->getPost('status', 'int'),
                    'created_time' => date('Y-m-d h:m:s'),
                    'updated_time' => date('Y-m-d h:m:s'),
                    'ip_address'    => '0',
                    'status' => $this->request->getPost('status'),
                ));
                if($video->save())
                {
                    $videoDescription = new VideoDescription();
                    $videoDescription->assign(array(
                        'video_id'  => $video->getId(),
                        'name'      => $this->request->getPost('name'),
                        'name_vn'      => $this->request->getPost('name'),
                        'short_name'      => $this->request->getPost('short_name'),
                        'description'   => $this->request->getPost('description'),
                    ));
                    $videoDescription->save();

                    $videoLink = new VideoCategoryLink();
                    $videoLink->assign(array(
                        'video_id'  => $video->getId(),
                        'category_id'      => $this->request->getPost('category_id'),
                        'position'      => 0,
                    ));
                    $videoLink->save();

                    //Check if the user has uploaded files
                    if ($this->request->hasFiles() == true) {
                        if ($this->request->hasFiles() == true) {
                            //Print the real file names and their sizes
                            $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $video->getId() , 'image_id' => 0 , 'object_type' => 'video' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                        }
                    }

                    return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
                }
                $this->flash->error($video->getMessages());
            }
        }
        $this->view->form = $form;
    }

    public function editAction($id)
    {
        $uploadFile = new UploadFile();
        $uploadFile->loadLibraryScript();

        $this->assets
            ->addJs('vendor/backend/js/video/video.js');

        $video = Video::findFirstById($id);
        $videoDescription = VideoDescription::find(array(
            "video_id = $id"
        ))->getFirst();
        
        $videoCategoryLink = VideoCategoryLink::findFirst("video_id = $id");

        //die(print $id);
        if(!$video)
        {
            $this->flash->error("Video was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }

        $form = new FormCreateVideo($video , array('name' => 'video' , 'edit' => true));
        $form->setAction($this->getBackendUrl() . '/' . $this->urlVideo . '/edit/' . $id);
        $formDescription = new FormCreateVideo($videoDescription , array('edit' => true));
        $formCategoryLink = new FormCreateVideo($videoCategoryLink , array('edit' => true));
        $tab = $this->request->get('tab') ? $this->request->get('tab') : 'general';

        if($this->request->getPost())
        {
            switch($tab)
            {
                case 'general':
                    if($form->isValid($this->request->getPost()) != false)
                    {
                        $video->assign(array(
                            'imdb' => 0 ,
                            'national_id'           => $this->request->getPost('national_id'),
                            'duration'              => $this->request->getPost('duration'),
                            'year_product'          => $this->request->getPost('year_product'),
                            'year_publish'          => $this->request->getPost('year_publish'),
                            'is_vip' => 'N',//$this->request->getPost('is_vip'),
                            'hot_month'             => $this->request->getPost('status' , 'int'),
                            'created_user'          => 1,//$this->request->getPost('status', 'int'),
                            'published_user'        => 1,//$this->request->getPost('status', 'int'),
                            //'created_time'          => date('Y-m-d h:m:s'),
                            //'updated_time'          => date('Y-m-d h:m:s'),
                            'ip_address'            => '0',
                            'status'                => $this->request->getPost('status'),
                        ));

                        if($video->save())
                        {
                            $videoDescription->assign(array(
                                'video_id'  => $video->getId(),
                                'name'      => $this->request->getPost('name'),
                                'name_vn'      => $this->request->getPost('name'),
                                'short_name'      => $this->request->getPost('short_name'),
                                'description'   => $this->request->getPost('description'),
                            ));

                            if($videoDescription->update() == false)
                            {
                                $this->flash->error($videoDescription->getMessages());
                            }

                            $videoCategoryLink->assign(array(
                                'video_id'  => $video->getId(),
                                'category_id'      => $this->request->getPost('category_id'),
                                'position'      => 0,
                            ));

                            /*$query = $this->modelsManager->createQuery("UPDATE \Backend\Modules\Video\Models\VideoCategoryLink set category_id = ?0 WHERE video_id = ?1");
                            $updateVideoCategoryLink = $query->execute(array(
                                0 => $this->request->getPost('category_id'),
                                1 => $video->getId()
                            ));*/

                            if(!$videoCategoryLink->save())
                            {
                                $this->flash->error($videoCategoryLink->getMessages());
                            }

                            //Check if the user has uploaded files
                            if ($this->request->hasFiles() == true) {
                                $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $video->getId() , 'object_type' => 'video' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                            }

                            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
                        }
                        $this->flash->error($video->getMessages());
                    }
                    break;

                case 'album':
                    if ($this->request->hasFiles() == true) {
                        $paramUpload = array(
                            'folder_upload' => 'files' ,
                            'object_id' => $video->getId() ,
                            'object_type' => 'video' ,
                            'type' => 'A' ,
                            'position' => 0
                        );
                        $uploadFile->doUpload($paramUpload , Common::listThumbnailOptionA());
                    }
                    break;

                default:
                    die(print '123');
                    return false;
                    break;
            }
        }

        $this->view->videoActorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_id = :video_id:', array('artist_type' => Artist::ACTOR , 'video_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();


        $this->view->videoDirectorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_id = :video_id:', array('artist_type' => Artist::DIRECTOR , 'video_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();

        
        $this->view->videoFileLinks = VideoFileLink::find(array(
            "video_id = $id"
        ));

        $this->view->videoGroupLinks = VideoGroupLink::find(array(
            "video_id = $id"
        ));
        $this->view->tab = $tab;
        $this->view->form = $form;
        $this->view->formDescription = $formDescription;
        $this->view->formCategoryLink = $formCategoryLink;
        $this->view->video = $video;
    }

    public function deleteAction($id)
    {
        $video = Video::findFirstById($id);

        if(!$video->delete())
        {
            $this->flash->error($video->getMessages());
        }
        else
        {
            $this->flash->success("Video was deleted");
        }

        return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
    }

    public function loadArtistAction()
    {       
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $artistType = $this->request->get('type') ? $this->request->get('type') : 1;

        $artists = Artist::find(array(
             "artist_type = $artistType"
        ));

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $artists,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(                
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
        if($artistType == Artist::DIRECTOR)
        {
            $this->view->render("video", "modal/modal_director");
            return ;
        }
        $this->view->render("video", "modal/modal_artist");
    }

    public function addArtistToVideoAction()
    {

        $this->view->disable();
        $json = array();
        $json['success'] = false;
        if($this->request->isPost() == true)
        {
            $video_id = $this->request->getQuery('video_id' , 'int');

            if($this->request->getPost('selectArtist') && $video_id > 0)
            {
                $selectActors = $this->request->getPost('selectArtist');

                $data = array();
                foreach($selectActors as $actorId)
                {
                    $checkActorHaveVideo = VideoArtistLink::find(array(
                        "video_id = $video_id AND artist_id = $actorId"
                    ))->count();

                    if($checkActorHaveVideo <= 0)
                    {
                        $selectActor = Artist::findFirstById($actorId)->toArray();
                        if($selectActor)
                        {
                            $videoArtistLink = new VideoArtistLink();
                            $videoArtistLink->setVideoId($video_id);
                            $videoArtistLink->setArtistId($actorId);
                            if($videoArtistLink->save())
                            {
                                $data[] = $selectActor;
                            }
                        }
                    }
                }
                if($data)
                {
                    $json['data'] = $data;
                    $json['success'] = true;
                }
            }
        }
        echo json_encode($json);
    }

    public function searchArtistAction()
    {
        $this->view->setTemplateAfter('empty');      

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
         $artists = Artist::find(array(
             "gender = 0"
         ));

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $artists,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(                
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        //$this->view->pager = $pager;
        $this->view->setVar('pager', $pager);

        $this->view->render('video' , 'searchActor');

        $json['success'] = true;
        $json['data'] = $this->view->getContent();
        
        $this->response->setContent(json_encode($json));
        //Return the response
        return $this->response->send();
    }

    public function removeArtistAction()
    {
        $this->view->disable();
        $json = array();
        $json['success'] = false;

        if($this->request->isPost() == true)
         {
             if($this->request->getPost('selectArtist'))
             {
                 $selectedActors = $this->request->getPost('selectArtist');
                 $video_id = $this->request->getPost('video_id' , 'int');

                 $data = array();
                 foreach($selectedActors as $actorId)
                 {
                     $videoArtistLink = VideoArtistLink::find(array(
                         "video_id = $video_id AND artist_id = $actorId",
                         //'hydration' => Resultset::HYDRATE_OBJECTS
                     ))->getFirst();

                     if($videoArtistLink)
                     {
                        if($videoArtistLink->delete())
                        {
                            $data[] = $videoArtistLink->toArray();
                            $json['success'] = true;
                        }
                     }
                 }
                 if($data)
                 {
                     $json['data'] = $data;
                     $json['success'] = true;
                 }
             }
        }
        $this->response->setContent(json_encode($json));
        //Return the response
        return $this->response->send();
    }

    public function loadFileVideoAction()
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $videoFiles = VideoFile::find();

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $videoFiles,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
    }

    public function addFileToVideoAction()
    {
        $this->view->disable();
        $json = array();
        $json['success'] = false;
        if($this->request->isPost() == true)
        {
            $video_id = $this->request->getQuery('video_id' , 'int');

            if($this->request->getPost('selectVideoFile') && $video_id > 0)
            {
                $selectVideoFile = $this->request->getPost('selectVideoFile');
                $data = array();
                foreach($selectVideoFile as $videoFileId)
                {
                    $checkVideoFileHaveVideo = VideoFileLink::find(array(
                        "video_id = $video_id AND video_file_id = $videoFileId"
                    ))->count();

                    if($checkVideoFileHaveVideo <= 0)
                    {
                        $selectVideoFile = VideoFile::findFirstById($videoFileId)->toArray();

                        if($selectVideoFile)
                        {
                            $videoFileLink = new VideoFileLink();
                            $videoFileLink->setVideoId($video_id);
                            $videoFileLink->setVideoFileId($videoFileId);
                            if($videoFileLink->save())
                            {
                                $data[] = $selectVideoFile;
                            }
                            else
                            {
                                die(print_r($videoFileLink->getMessages()));
                            }
                        }
                    }
                }
                if($data)
                {
                    $json['data'] = $data;
                    $json['success'] = true;
                }
            }
        }
        echo json_encode($json);
    }

    public function removeFileVideoLinkAction()
    {
        $this->view->disable();
        $json = array();
        $json['success'] = false;

        if($this->request->isPost() == true)
        {
            if($this->request->getPost('selectedFile'))
            {
                $selectedVideoFileLink = $this->request->getPost('selectedFile');

                $video_id = $this->request->getPost('video_id' , 'int');

                $data = array();
                foreach($selectedVideoFileLink as $videoFileId)
                {
                    $videoFileLink = VideoFileLink::find(array(
                        "video_id = $video_id AND video_file_id = $videoFileId",
                        //'hydration' => Resultset::HYDRATE_OBJECTS
                    ))->getFirst();

                    if($videoFileLink)
                    {
                        if($videoFileLink->delete())
                        {
                            $data[] = $videoFileLink->toArray();
                            $json['success'] = true;
                        }
                        else
                        {
                            die(print_r($videoFileLink->getMessages()));
                        }
                    }
                }
                if($data)
                {
                    $json['data'] = $data;
                    $json['success'] = true;
                }
            }
        }
        $this->response->setContent(json_encode($json));
        //Return the response
        return $this->response->send();
    }

    public function loadVideoGroupAction()
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $videoGroups = VideoGroup::find();

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $videoGroups,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
    }

    public function addVideoGroupToVideoAction()
    {
        $this->view->disable();
        $json = array();
        $json['success'] = false;
        if($this->request->isPost() == true)
        {
            $video_id = $this->request->getQuery('video_id' , 'int');

            if($this->request->getPost('selectVideoGroup') && $video_id > 0)
            {
                $selectVideoGroup = $this->request->getPost('selectVideoGroup');

                $data = array();
                foreach($selectVideoGroup as $videoGroupId)
                {
                    $checkHaveVideoGroup = VideoGroupLink::find(array(
                        "video_id = $video_id AND video_group_id = $videoGroupId"
                    ))->count();

                    if($checkHaveVideoGroup <= 0)
                    {
                        $selectVideoGroup = VideoGroup::findFirstById($videoGroupId)->toArray();

                        if($selectVideoGroup)
                        {
                            $videoGroupLink = new VideoGroupLink();
                            $videoGroupLink->setVideoId($video_id);
                            $videoGroupLink->setVideoGroupId($videoGroupId);
                            if($videoGroupLink->save())
                            {
                                $data[] = $selectVideoGroup;
                            }
                            else
                            {
                                die(print_r($videoGroupLink->getMessages()));
                            }
                        }
                    }
                }
                if($data)
                {
                    $json['data'] = $data;
                    $json['success'] = true;
                }
            }
        }
        echo json_encode($json);
    }

    public function removeVideoGroupLinkAction()
    {
        $this->view->disable();
        $json = array();
        $json['success'] = false;

        if($this->request->isPost() == true)
        {
            if($this->request->getPost('selectedVideoGroup'))
            {
                $selectedVideoGroupLink = $this->request->getPost('selectedVideoGroup');

                $video_id = $this->request->getPost('video_id' , 'int');

                $data = array();
                foreach($selectedVideoGroupLink as $videoGroupId)
                {
                    $videoGroupLink = VideoGroupLink::find(array(
                        "video_id = $video_id AND video_group_id = $videoGroupId",
                        //'hydration' => Resultset::HYDRATE_OBJECTS
                    ))->getFirst();

                    if($videoGroupLink)
                    {
                        if($videoGroupLink->delete())
                        {
                            $data[] = $videoGroupLink->toArray();
                            $json['success'] = true;
                        }
                        else
                        {
                            die(print_r($videoGroupLink->getMessages()));
                        }
                    }
                }
                if($data)
                {
                    $json['data'] = $data;
                    $json['success'] = true;
                }
            }
        }
        $this->response->setContent(json_encode($json));
        //Return the response
        return $this->response->send();
    }
}
